<template>
  <div>
    <el-button
      type="primary"
      icon="ele-Plus"
      @click="changeViewHandler"
      :disabled="category3Id === ''"
      >添加SPU</el-button
    >

    <el-table style="margin: 20px 0" stripe border :data="SPUs">
      <el-table-column width="80" label="序号" type="index"></el-table-column>
      <el-table-column label="SPU名称" prop="spuName"></el-table-column>
      <el-table-column label="SPU描述" prop="description"></el-table-column>
      <el-table-column width="250" label="操作">
        <template #="{ row }">
          <el-button
            type="success"
            icon="ele-Plus"
            @click="toAddSKUHandler(row)"
          ></el-button>
          <el-button
            type="warning"
            icon="ele-Edit"
            @click="toEditHandler(row)"
          ></el-button>
          <el-button
            type="info"
            icon="ele-InfoFilled"
            @click="showSKUListHandler(row)"
          ></el-button>
          <el-button
            type="danger"
            icon="ele-Delete"
            @click="removeHandler(row.id)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :total="total"
      :page-count="pages"
      v-model:page-size="limit"
      @size-change="getSPUs"
      v-model:current-page="page"
      @current-change="getSPUs"
      :page-sizes="[5, 10, 15]"
      layout="prev,pager,next,jumper,->,sizes,total"
    ></el-pagination>

    <el-dialog
      v-if="showSPUInfo"
      v-model="isShowSPUInfoDialog"
      :title="showSPUInfo.spuName"
    >
      <el-table :data="skuList" v-loading="skuListLoading">
        <el-table-column label="名称" prop="skuName"></el-table-column>
        <el-table-column label="价格" prop="price"></el-table-column>
        <el-table-column label="重量" prop="weight"></el-table-column>
        <el-table-column label="默认图片">
          <template #="{ row }">
            <img :src="row.skuDefaultImg" style="width: 100px" />
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "SPUList",
});
</script>

<script lang="ts" setup>
import VIEW_TYPE from "@/views/product/spu/vueTypes";
import { useCategorySelectorStore } from "@/stores/categorySelector";
import { storeToRefs } from "pinia";
import { watch, ref, computed } from "vue";
import * as apis from "@/api/spu";
import * as skuApis from "@/api/sku";
import { ElMessage, ElMessageBox } from "element-plus";

import type { ISPU } from "@/api/spu";
import type { ISKU } from "@/api/sku";

/**
 * 定义事件
 */
const emits = defineEmits(["change-view"]);

function changeViewHandler() {
  emits("change-view", VIEW_TYPE.SPU_FORM);
}

/**
 * 导入仓库
 */
const categorySelectorStore = useCategorySelectorStore();
const { category3Id } = storeToRefs(categorySelectorStore);

/**
 * spu 列表
 */
const SPUs = ref<ISPU[]>([]);
// 总页面数
const pages = ref(0);
// 每页显示条数
const limit = ref(5);
// 当前页
const page = ref(1);
// 总条数
const total = ref(0);

// 要查看SKU列表的SPU的信息
const showSPUInfo = ref<ISPU>();

// 对话框的状态
const isShowSPUInfoDialog = computed({
  get() {
    return !!showSPUInfo.value;
  },
  set(newVal) {
    // newVal 其实就是对话框的状态，但是因为 isShowSPUInfoDialog 是一个计算属性，有 get的，所以对话框无法同步修改这个 isShowSPUInfoDialog 的值，因为isShowSPUInfoDialog 的值是取决于 showSPUInfo 这个变量
    // console.log(123, newVal);
    showSPUInfo.value = undefined;
  },
});

// SKU的列表
const skuList = ref<ISKU[]>([]);

// SKU列表加载的loading状态，把这个值通过 v-loading 指令绑定到 表格中
// 数据开始加载的时候显示 loading，加载完成以后隐藏 loading
const skuListLoading = ref(false);

async function getSPUs() {
  if (category3Id.value === "") return (SPUs.value = []);

  try {
    const res = await apis.requestSPUs(
      category3Id.value as number,
      page.value,
      limit.value
    );

    SPUs.value = res.records;
    pages.value = res.pages;
    page.value = res.current;
    total.value = res.total;
  } catch (e) {
    ElMessage.error("请求 SPU 列表数据失败");
  }
}

/**
 * 监听 category3Id 的变化并立即执行
 * 当 category3Id 不为空的时候，发送请求，获取当前分类下的 spu 列表
 */
watch(category3Id, getSPUs, {
  immediate: true,
});

/**
 * 当每页显示条数发生改变的时候
 */
// function sizeChangeHandler() {
//   getSPUs();
// }

/**
 * 当当前页发生改变的时候
 */
// function currentChangeHandler() {
//   getSPUs();
// }

/**
 * 点击去编辑
 */
function toEditHandler(row: ISPU) {
  emits("change-view", VIEW_TYPE.SPU_FORM, row);
}

/**
 * 点击跳转添加 sku
 */
function toAddSKUHandler(row: ISPU) {
  emits("change-view", VIEW_TYPE.SKU_FORM, row);
}

/**
 * 删除 SPU
 */
async function removeHandler(id: number) {
  try {
    await ElMessageBox.confirm("你确定要删除吗？", "提示");

    await apis.requestDeleteSPU(id);

    ElMessage.success("删除成功");
    getSPUs();
  } catch (e) {
    if (e !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
}

/**
 * 查看指定的SPU下的SKU列表
 */
async function showSKUListHandler(row: ISPU) {
  // 显示 loading
  skuListLoading.value = true;
  showSPUInfo.value = row;

  // 请求 当前 SPU 下的 SKU 列表数据，并渲染在dialog 的table中
  try {
    skuList.value = await skuApis.requestSKUList(row.id);
  } catch (e) {
    ElMessage.error("sku列表数据获取失败");
  } finally {
    // 最终执行的代码，这里执行代码无论是 try 还 catch 都会被执行
    skuListLoading.value = false;
  }
}
</script>
